<template>
  <div>
    <!-- 添加或修改资产清单表对话框 -->
    <el-dialog ref="editDialog" v-model="openFlag" title="盘点" width="50%" append-to-body>
      <!-- 基本信息部分 -->
      <div>基本信息</div>
      <el-form ref="baseForm" :model="baseForm" :rules="baseFormRules" label-width="100">
        <el-form-item label="名称" prop="title">
          <el-input v-model="baseForm.title" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="盘点人" prop="userId">
          <user-select v-model="baseForm.userId" placeholder="请输入"></user-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input type="textarea" v-model="baseForm.remark" placeholder="请输入" />
        </el-form-item>
      </el-form>
      <!-- 盘点范围部分 -->
      <div>盘点范围</div>
      <el-form ref="rangeForm" :model="rangeForm" :rules="rangeFormRules" label-width="100">
        <el-row>
          <el-col :span="12">
            <el-form-item label="类别" prop="categoryId">
              <category-select v-model="rangeForm.categoryId" placeholder="请输入" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="仓库" prop="warehouseId">
              <warehouse-select v-model="rangeForm.warehouseId" placeholder="请输入" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="资产状态" prop="status">
          <el-select v-model="rangeForm.status" placeholder="请选择">
            <el-option label="在用" value="in_use"></el-option>
            <el-option label="闲置" value="idle"></el-option>
            <el-option label="维修中" value="under_repair"></el-option>
            <el-option label="报废" value="scrapped"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="使用部门" prop="department">
          <el-input v-model="rangeForm.department" placeholder="请输入使用部门" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-row type="flex" justify="end">
          <el-button type="primary" @click="save">保存</el-button>
          <el-button @click="cancel">取消</el-button>
        </el-row>
      </div>
    </el-dialog>

    <!-- 选择对话框 -->
    <choose-dialog ref="chooseDialog" @sub="onChooseSub"></choose-dialog>
  </div>
</template>

<script>
import api from "./api.js";
import UserSelect from "@/components/User/UserSelect.vue";
import ChooseDialog from "@/components/Asset/ChooseDialog.vue";
import CategorySelect from "@/components/Asset/CategorySelect.vue";
import WarehouseSelect from "@/components/Warehouse/WarehouseSelect.vue";

export default {
  components: {
    WarehouseSelect,
    CategorySelect,
    ChooseDialog,
    UserSelect
  },
  data() {
    return {
      openFlag: false,  // 控制对话框的开关
      tableData: {
        loading: false,
        list: []
      },
      deletedItem: [], // 存储被删除的资产
      currentRow: null,
      isEdit: false, // 是否为编辑模式
      actionType: '',  // 操作类型
      baseForm: {  // 基本信息
        title: '',
        userId: '',
        remark: '',
      },
      rangeForm: {  // 盘点范围
        categoryId: null,
        warehouseId: null,
        status: '',   
        company: '',  
        managerId: '', 
        department: '' 
      },
      // 基本信息的校验规则
      baseFormRules: {
        title: [
          { required: true, message: '请输入名称', trigger: 'blur' },
          { max: 50, message: '名称不能超过50个字符', trigger: 'blur' }
        ],
        userId: [
          { required: true, message: '请选择盘点人', trigger: 'blur' }
        ],
        remark: [
          { max: 200, message: '备注不能超过200个字符', trigger: 'blur' }
        ]
      },
      rangeFormRules: {
        categoryId: [
          { required: true, message: '请选择类别', trigger: 'blur' }
        ],
        warehouseId: [
          { required: true, message: '请选择仓库', trigger: 'blur' }
        ],
        status: [
          { required: true, message: '请选择资产状态', trigger: 'blur' }
        ],
        department: [
          { max: 20, message: '部门名称不能超过20个字符', trigger: 'blur' }
        ]
      }
    };
  },

  methods: {
    // 打开对话框，并根据操作类型加载数据
    open({ actionType, row }) {
      this.openFlag = true;
      this.reset();
      this.actionType = actionType;
      if (actionType === 'edit') {
        api.detail(row).then(response => {
          Object.assign(this.baseForm, response); // 合并返回的表单数据
          this.tableData.list = response.items; // 加载资产列表
        }).catch(error => {
          this.$message.error("加载数据失败！");
        });
      }
    },

    // 关闭对话框
    close() {
      this.openFlag = false;
    },

    // 重置表单数据
    reset() {
      this.baseForm = {
        title: '',
        userId: '',
        remark: '',
      };
      this.rangeForm = {
        categoryId: null,
        warehouseId: null,
        status: '',  
        company: '',   
        managerId: '', 
        department: '' 
      };
    },

    // 取消操作
    cancel() {
      this.reset();
      this.close();
    },

    // 选择资产时的操作
    handleChoose() {
      this.$refs.chooseDialog.open();
    },

    // 删除行
    handleDelete({ row, $index }) {
      if (this.actionType === 'edit') {
        this.deletedItem.push(row);  // 记录删除的资产
      }
      this.tableData.list.splice($index, 1);  // 从列表中删除该行
    },

    // 保存表单数据
    save() {
      this.$refs.baseForm.validate((valid) => {
        // 验证基础信息
        if (valid) {
          this.$refs.rangeForm.validate((rangeValid) => {
            // 验证盘点范围
            if (rangeValid) {
              const params = {
                baseForm: this.baseForm,
                rangeForm: this.rangeForm
              };
              api.save(params).then(response => {
                this.$emit("sub");
                this.close();
                this.$message.success("保存成功！");
              }).catch(error => {
                this.$message.error("保存失败，请稍后重试！");
              });
            } else {
              this.$message.error("请检查盘点范围是否正确！");
            }
          });
        } else {
          this.$message.error("请检查基本信息是否正确！");
        }
      });
    },

    // 选择资产后的回调
    onChooseSub(selected) {
      if (selected) {
        selected.forEach((item) => {
          let row = { ...item }; // 创建新的对象防止直接修改源数据
          row.sourceId = row.id;
          delete row.id; // 删除源ID
          this.tableData.list.push(row);  // 添加到资产列表
        });
      }
    }
  }
}
</script>

<style scoped>
.dialog-footer {
  padding: 10px;
  text-align: right;
}
</style>
